import lib.arithmetics as arithmetics
import lib.problem as problem
import unittest


class Problem030(problem.Problem):
	def __init__(self):
		problem.Problem.__init__(self, 30)
		self.powers = []
		self.currentPowers = 0
		
		
	def initPowersOfDigits(self, power):
		self.powers = []
		for i in range(10):
			self.powers.append( int(pow(i, power)) )
		self.currentPowers = power
		
	
	def digitsOf(self, n):
		digits= []
		powerOf10 = 1
		
		while powerOf10 <= n:
			digits.insert(0, (n / powerOf10) % 10 )
			powerOf10 *= 10
			
			
		return digits
		
	
	def sumOfDigitsPowers(self, n, power):
		result = 0
		
		digits = self.digitsOf(n)
		
		for digit in digits:
			result += self.powers[digit]
			#result += pow(digit, power)
			if result > n:
				return -1
		
		return result
	
	
	def numsEqualToSumOfPowers(self, power, max=10000):
		solution = []
		sumOfPowers = 0
		n = 10
		
		self.initPowersOfDigits(power)
		
		while n <= max:
			sumOfPowers = self.sumOfDigitsPowers(n, power)
			if n == sumOfPowers:
				solution.append(n)
			n += 1

		return solution
		
	def solve(self):
		return arithmetics.sum( self.numsEqualToSumOfPowers(5, 1000000) )
	
	
	
class Problem030Tester(unittest.TestCase):
	
	def setUp(self):
		self.p030 = Problem030()
		
	def testDigitsOf1634(self):
		d = self.p030.digitsOf(1634)
		self.assertEquals([1,6,3,4], d)
		
	def testInitPowersOfDigits(self):
		self.p030.initPowersOfDigits(5)
		self.assertEquals([0, 1, 32, 243, 1024, 3125, 7776, 16807, 32768, 59049], self.p030.powers)
		
	def testSumOfDigitsPowers1634_4(self):
		self.p030.initPowersOfDigits(4)
		s = self.p030.sumOfDigitsPowers(1634,4)
		self.assertEquals(1634, s)
		
	def testNumsEqualToSumOfPowers4(self):
		solution = self.p030.numsEqualToSumOfPowers(4)
		self.assertEquals([1634, 8208, 9474], solution)
	
	
	def testNumsEqualToSumOfPowers5(self):
		solution = self.p030.numsEqualToSumOfPowers(5, 1000000)
		self.assertEquals([-1], solution)
		
		
	
#	def testSolve(self):
#		self.assertEquals(-1, self.p030.solve())
